<?php

namespace Xin\Setting\Laravel;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Xin\Setting\Exceptions\InvalidConfigureException;
use Xin\Setting\SettingManager;

/**
 * 配置模型
 *
 * @property int type
 * @property int sort
 * @property string value
 * @property string extra
 * @property int group
 */
class DatabaseSetting extends Model
{
	/**
	 * @var string
	 */
	protected $table = 'settings';

	/**
	 * @var array
	 */
	protected $guarded = [];

	/**
	 * @var array
	 */
	protected $appends = [
		'type_text',
		'group_text',
	];

	/**
	 * @return SettingManager
	 */
	protected function manager()
	{
		return app('setting');
	}

	/**
	 * 获取数据分组
	 *
	 * @return Attribute
	 * @throws InvalidConfigureException
	 */
	protected function groupText(): Attribute
	{
		$groups = $this->manager()->getGroupList();

		return Attribute::get(function ($value, $attributes) use ($groups) {
			$group = $attributes['group'];

			return isset($groups[$group]) ? $groups[$group] : "无";
		});
	}

	/**
	 * 获取数据类型
	 *
	 * @return Attribute
	 * @throws InvalidConfigureException
	 */
	protected function typeText(): Attribute
	{
		$types = $this->manager()->getTypeList();

		return Attribute::get(function ($value, $attributes) use ($types) {
			$type = $attributes['type'];

			return isset($types[$type]) ? $types[$type] : "无";
		});
	}
}
